package com.example.juc.kkb.synchronizedandlock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 新版写法
 */
public class MyCondition2 {
    private int number = 0;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    /**
     * ⽣产
     */
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while (number != 0) {
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t " +
                    number);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 消费
     */
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //1. 判断
            while (number == 0) {
                //this.wait();
                condition.await();
            }
            //2. ⼲活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t " +
                    number);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}